// app/controller/user.js
const Controller = require('egg').Controller;
const bcrypt = require('bcryptjs');

class UserController extends Controller {
  async index() {
    const { ctx } = this;
    const jwt = this.app.jwt;
    console.log('000', this.app.config.jwt.secret, ctx.header.authorization)
    const token = jwt.sign({ userId: '123' }, this.app.config.jwt.secret);
    const users = await ctx.model.User.find();
    console.log('token', token)
    ctx.body = users
  }
  async registration() {
    const { ctx, service, app } = this
    // 获取 POST 请求参数
    const { username, password, email } = ctx.request.body;

    console.log('registration', ctx.request.body, ctx.params )

    // 定义参数验证规则
    const rule = {
      username: { type: 'string' },
      password: { type: 'string', min: 6, required: true, message: '密码不能为空', },
      email: { type: 'string', min: 0, max: 120, required: true, message: '邮箱格式不正确', },
    };

    ctx.validate(rule);

    // 调用 Service 方法
    const result = await service.user.registration({ username, password, email });
    if(result.password ) delete result.password
    if(result) {
      // 通常情况下，注册成功后需要返回一个token给前端。这个token可以用于后续的身份验证、权限控制等操作。
      const jwt = this.app.jwt;
      const token = jwt.sign({ username }, app.config.jwt.secret, { expiresIn: '24h' })
      result.token = token
      ctx.body = ctx.showSuccess(result)
    } else {
      ctx.body = {
        code: ctx.errorMap.registerFailed.code,
        message: ctx.errorMap.registerFailed.message,
      }
    }
  }

  async login() {
    const { ctx, service, app } = this
    // 获取 POST 请求参数
    const { username, password } = ctx.request.body;

    console.log('login', ctx.request.body, ctx.params )

    // 定义参数验证规则
    const rule = {
      username: { type: 'string', required: true },
      password: { type: 'string', min: 6, required: true, message: '密码不能为空', }
    };

    // 验证参数合法性
    ctx.validate(rule);

    // 调用 Service 方法
    const result = await service.user.login({ password, username });
    // console.log('查询结果', result)
    if(result) {
      // 验证密码是否正确
      const isMatch = await bcrypt.compare(password, result.password);
      console.log('ss', isMatch)
      if (isMatch) {
        // 密码正确，返回用户信息
         // 密码正确，生成 Token
         const jwt = this.app.jwt;
         const token = jwt.sign({ username }, app.config.jwt.secret, { expiresIn: '24h' });
         //  result = Object.assign(result, {token})
         result.password &&  delete result.password
         result.token = token
        //  console.log('result', result)
        ctx.body = ctx.showSuccess(Object.assign({}, result, {token}))
      } else {
        // 密码不正确，返回错误信息
        ctx.body = {
          code: ctx.errorMap.passwordError.code,
          message: ctx.errorMap.passwordError.message,
        }
      }
    } else {
      ctx.body = {
        code: ctx.errorMap.userNotExist.code,
        message: ctx.errorMap.userNotExist.message,
      }
    }

  }

  async getCurregntUser () {
    const { ctx, service } = this
    console.log('user', ctx.state.user)
    const result = await service.user.getCurregntUser();
    if(result) {
      delete result.password
      ctx.body = ctx.showSuccess(result)
    } else {
      ctx.body = {
        code: ctx.errorMap.userNotExist.code,
        message: ctx.errorMap.userNotExist.message,
      }
    }

  }
  async updateUser() {
    console.log('updateUser1')
    const { ctx, service } = this
    const { user } = ctx.request.body;
    let { username } = ctx.state.user

    const rule = {
      email: { type: 'string', required: false, min: 0, max: 120, message: '邮箱格式不正确', },
      bio: { type: 'string', required: false, min: 6, message: '密码不能为空', },
      image: { type: 'string', required: false, message: '图片不能为空', },
    };

    if(!username) {
      ctx.throw(ctx.errorMap.paramsError.code, 'user 参数不能为空');
    }

    const { email, bio, image } = user
    // 确保三个参数不能全为空
    if (!email && !bio && !image) {
      ctx.throw(ctx.errorMap.paramsError.code, 'email, bio, image 不能全为空');
    }

    ctx.validate(rule);

    const result = await service.user.updateUser();
    // 判断更新是否成功
    if(result.ok === 1 && result.nModified === 1) {
      ctx.body = ctx.showSuccess(result)
    } else {
      ctx.body = {
        code: ctx.errorMap.updateFail.code,
        message: ctx.errorMap.updateFail.message,
      }
    }
  }
  async getProfile() {
    const { ctx, service } = this
    const { username } = ctx.params;
    const rule = {
      username: { type: 'string', required: false, message: '用户名不能为空', },
    };
    ctx.validate(rule);
    // 查询 Profile 数据
    const result = await service.user.getProfile();
    console.log(result)
    if(result) {
      ctx.body = ctx.showSuccess(result)
    } else {
      ctx.body = {
        code: ctx.errorMap.userNotExist.code,
        message: ctx.errorMap.userNotExist.message,
      }
    }
  }
  async followUser() {
    const { ctx, service } = this
    console.log(ctx.params.username)
    const rule = {
      username: { type: 'string', required: false, message: '用户名不能为空', },
    };
    ctx.validate(rule);
    const result = await service.user.followUser();
    if(result) {
      ctx.body = ctx.showSuccess(result)
    } else {
      ctx.body = {
        code: ctx.errorMap.followFail.code,
        message: ctx.errorMap.followFail.message,
      }
    }
  }
  async unfollowUser() {
    const { ctx, service } = this
    console.log(ctx.params.username)
    const rule = {
      username: { type: 'string', required: false, message: '用户名不能为空', },
    };
    ctx.validate(rule);
    const result = await service.user.unfollowUser();
    if(result.ok === 1 && result.nModified === 1) {
      ctx.body = ctx.showSuccess(result)
    } else {
      ctx.body = {
        code: ctx.errorMap.unfollowFail.code,
        message: ctx.errorMap.unfollowFail.message,
      }
    }
  }
}

module.exports = UserController;